package com.rfsp.mcp.controller.hos;

import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.RedirectView;

import com.github.pagehelper.PageInfo;
import com.rfsp.common.base.ResultListVO;
import com.rfsp.common.base.ResultVO;
import com.rfsp.common.interceptor.Token;
import com.rfsp.common.interceptor.TokenType;
import com.rfsp.common.log.TrcMsg;
import com.rfsp.common.pojo.po.OrgPO;
import com.rfsp.common.pojo.po.UserPO;
import com.rfsp.common.pojo.sdto.PageSDTO;
import com.rfsp.common.service.AreaService;
import com.rfsp.common.service.OrgService;
import com.rfsp.common.service.ParamService;
import com.rfsp.common.service.UserService;
import com.rfsp.common.shiro.ShiroUtils;
import com.rfsp.common.util.DateUtil;
import com.rfsp.common.util.DecimalFormatUtil;
import com.rfsp.common.util.FileUtil;
import com.rfsp.common.util.StringUtil;
import com.rfsp.common.util.XssUtils;
import com.rfsp.mcp.enums.MiPayDataTypeEnum;
import com.rfsp.mcp.pojo.dto.FinanceCancelDTO;
import com.rfsp.mcp.pojo.dto.FinanceDTO;
import com.rfsp.mcp.pojo.dto.MiPayLogDTO;
import com.rfsp.mcp.pojo.dto.OrgSubjectInfoDto;
import com.rfsp.mcp.pojo.po.AuthPO;
import com.rfsp.mcp.pojo.po.OrgYbjPO;
import com.rfsp.mcp.pojo.sdto.FinanceSDTO;
import com.rfsp.mcp.pojo.sdto.MiPayLogSDTO;
import com.rfsp.mcp.pojo.sdto.ProductSDTO;
import com.rfsp.mcp.pojo.vo.FinanceVO;
import com.rfsp.mcp.pojo.vo.MiPayLogVO;
import com.rfsp.mcp.pojo.vo.PfmVO;
import com.rfsp.mcp.pojo.vo.ProductVO;
import com.rfsp.mcp.service.AuthService;
import com.rfsp.mcp.service.FinanceService;
import com.rfsp.mcp.service.OrgYbjService;
import com.rfsp.mcp.service.PayLogService;
import com.rfsp.mcp.service.PfmService;
import com.rfsp.mcp.service.ProductService;
import com.rfsp.mcp.service.interfaceclient.WSOrgSubjectInfoService;

@RequiresRoles(value={"mcp_hos"}, logical= Logical.AND)
@Controller("HosFinanceController")
@RequestMapping("/hos/finance")
public class HosFinanceController extends HosController {
	
	public Logger logger = LoggerFactory.getLogger(HosFinanceController.class);
	
	@Autowired
	ProductService productService;
	
	@Autowired
	FinanceService financeService;
	
	@Autowired
	AreaService areaCodeService;
	
	@Autowired
	OrgYbjService orgYbjService;
	
	@Autowired
	AuthService authService;
	
	@Autowired
    OrgService orgService;
	
	@Autowired
    UserService userService;
	
	@Autowired
	PfmService pfmService;

	@Autowired
	PayLogService payLogService;

	@Autowired
    ParamService paramService;
	@Autowired
	OrgYbjService ybjSerivce;

	@Autowired
	WSOrgSubjectInfoService orgSubjectInfoService;

	private static final String QUERY_REASON = "用户自查";

	@RequestMapping("/")
    public String index1(ModelMap model, PageSDTO pageSdto, FinanceSDTO sdto) {
        return index(model,pageSdto,sdto);
    }
    @RequestMapping("/index")
    public String index(ModelMap model, PageSDTO pageSdto, FinanceSDTO sdto) {
    	logger.info(TrcMsg.getMsg(TrcMsg.METHOD_BEGIN, "index"));
		//获取登录时选择的医保平台vo
		PfmVO pfm = ShiroUtils.getAttribute("mcp_pfm");
		OrgYbjPO orgYbjPO = ShiroUtils.getAttribute("org_ybj");


    	UserPO userPO = ShiroUtils.getCurrentUser();
        sdto.setOrgId(userPO.getOrgId());
        
        if(StringUtils.isNotBlank(sdto.getCounty())) {
        	sdto.setAreaCode(sdto.getCounty());
        }else if(StringUtils.isNotBlank(sdto.getCity())) {
        	sdto.setAreaCode(sdto.getCity().substring(0, 4));
        }else if(StringUtils.isNotBlank(sdto.getProvince())) {
        	sdto.setAreaCode(sdto.getProvince().substring(0, 2));
        }
        if(StringUtils.isNotBlank(sdto.getBankOrgName())) {
        	sdto.setBankOrgName(XssUtils.replaceXssAll(sdto.getBankOrgName()));
        }

		sdto.setPfmId(pfm.getId());
		sdto.setOrgYbjId(orgYbjPO.getId());
    	
        PageInfo<FinanceVO> pageInfo = financeService.get(sdto, pageSdto);
        financeService.combo(pageInfo.getList());
        
        ResultListVO<FinanceVO> vo = ResultListVO.success(pageInfo,sdto);
        model.put("vo", vo);
        
        logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "index"));
        return "hos/finance/index";
    }
    
    

    @Token
    @GetMapping("/create")
    public String createForm(ModelMap model, FinanceDTO dto, BindingResult bindingResult) {
    	logger.info(TrcMsg.getMsg(TrcMsg.METHOD_BEGIN, "createForm"));
		//获取登录时选择的医保平台vo
		PfmVO pfm = ShiroUtils.getAttribute("mcp_pfm");
    	
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
    	
    	Calendar calendar = Calendar.getInstance();
    	String authStartTime = sdf.format(calendar.getTime());
    	dto.setAuthStartTime(authStartTime);
    	
    	calendar.add(Calendar.YEAR, 1);
    	calendar.add(Calendar.DAY_OF_YEAR, -1);
    	String authEndTime = sdf.format(calendar.getTime());
        if(StringUtils.isBlank(dto.getAuthEndTime())) {
        	dto.setAuthEndTime(authEndTime);
    	}
    	
    	//主体信息表链接使用id&aid
    	OrgPO orgPO = ShiroUtils.getCurrentOrg();
    	//OrgYbjPO orgYbjPO = orgYbjService.getYbjId(orgPO.getId(), pfm.getId());
        OrgYbjPO orgYbjPO = ShiroUtils.getAttribute("org_ybj");
    	dto.setOrgYBJId(orgYbjPO.getId());
    	dto.setOrgYBJAId(orgYbjPO.getAid());
    	if(StringUtils.isBlank(dto.getContactName())) {
    		dto.setContactName(XssUtils.replaceUnXssAll(orgPO.getContactName()));
    	}
    	if(StringUtils.isBlank(dto.getContactMobile())) {
    		dto.setContactMobile(orgPO.getContactMobile());
    	}

		if (null != pfm) {
			dto.setPfmId(pfm.getId());
			if (StringUtils.isNotBlank(pfm.getAreaCode())) {
				dto.setPfmAreaAddress(areaCodeService.getFullAddress(pfm.getAreaCode()));
			}
		}

    	model.put("dto",dto);
    	
    	ResultVO<FinanceDTO> result = ResultVO.success(dto);
        model.put("result", result);
        if(bindingResult.hasErrors()) {
            result.setMsg("操作失败");
        }
    	
        logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "createForm"));

		String itfType = pfm.getItfType().trim();
		if("0".equals(itfType))
			return "hos/finance/createForm";
		else
			return "hos/finance/createFormYBD";

    }
    
    
    @Token(TokenType.refresh)
    @PostMapping("/create")
    public ModelAndView create(ModelMap model, @ModelAttribute("dto") @Valid FinanceDTO dto, BindingResult result) {
    	logger.info(TrcMsg.getMsg(TrcMsg.METHOD_BEGIN, "create"));
    	
    	if(dto.getAuthId() != null) {
			AuthPO authPO = authService.get(dto.getAuthId());
			dto.setAuthAid(authPO.getAid());
			dto.setAuthStartTime(DateUtil.Date2String(authPO.getAuthStartTime(), "yyyy-MM-dd"));
			dto.setAuthEndTime(DateUtil.Date2String(authPO.getAuthEndTime(), "yyyy-MM-dd"));
		}
    	
    	PfmVO pfm = ShiroUtils.getAttribute("mcp_pfm");
    	dto.setPfmAreaAddress(pfm.getAreaCodeStr());
    	
    	if(result.hasErrors()) {
    		logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "create"));
    		return new ModelAndView(createForm(model,dto,result));
    	}
    	
    	String errorInfo = financeService.validateSave(XssUtils.replaceUnXss(dto));
    	
    	if(StringUtils.isNotBlank(errorInfo)) {
    		result.addError(new FieldError("dto", "global", errorInfo));
    		
    		logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "create"));
    		return new ModelAndView(createForm(model,dto,result));
    	}
    	
    	
    	try {
    		Map<String, Object> maps = financeService.saveFinance(XssUtils.replaceUnXss(dto));
    		financeService.savePDF(maps);
		} catch (Exception e) {
			logger.info("====>抛出异常，已修改回滚创建数据");
			e.printStackTrace();
			errorInfo = "系统异常，请拔打客服电话400-009-0001或通过在线客服问询处理。";
		}
    	
    	if(StringUtils.isNotBlank(errorInfo)) {
    		result.addError(new FieldError("dto", "global", errorInfo));
    		
    		logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "create"));
    		return new ModelAndView(createForm(model,dto,result));
    	}
    	
    	logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "create"));


		RedirectView redirectView = new RedirectView("./createSuccess");
		redirectView.setHttp10Compatible(false);
		return new ModelAndView(redirectView);
    }

	@GetMapping("/createSuccess")
	public String createSuccess(ModelMap model) {
		return "hos/finance/createSuccess";
	}

    @Token
    @GetMapping("/cancel")
    public String cancelForm(ModelMap model, FinanceCancelDTO dto) {
    	ResultVO<FinanceCancelDTO> vo = ResultVO.success(dto);
    	model.put("vo", vo);
    	model.put("dto", dto);
    	
        return "hos/finance/cancelForm";
    }

    @Token(TokenType.refresh)
    @PostMapping("/cancel")
    public String cancel(ModelMap model, @ModelAttribute("dto") @Valid FinanceCancelDTO dto, BindingResult result) {
    	logger.info(TrcMsg.getMsg(TrcMsg.METHOD_BEGIN, "cancel"));
    	
    	if(result.hasErrors()) {
    		return cancelForm(model,dto);
    	}
    	
    	String returnStr = null;
    	try {
    		returnStr = "2".equals(financeService.cancelFinance(XssUtils.replaceUnXss(dto)))?"操作成功，待资金方审批":"操作成功";
		} catch (Exception e) {
			e.printStackTrace();
			returnStr = "系统异常，请拔打客服电话400-009-0001或通过在线客服问询处理。";
		}
    	logger.info("returnStr="+returnStr);//1：未查看 2：已查看
    	
    	
    	
    	logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "cancel"));
    	return alertParentReload(model, returnStr);
    }
    
    


    @GetMapping("/cancelDetail")
    public String cancelDetail(ModelMap model, FinanceCancelDTO dto) {
    	logger.info(TrcMsg.getMsg(TrcMsg.METHOD_BEGIN, "cancelDetail"));
    	
    	FinanceVO financeVO = financeService.getBy2Id(dto.getId(), dto.getAid());
    	financeService.combo(financeVO);
    	
    	AuthPO authPO = authService.get(financeVO.getAuthId());
    	
    	
    	
    	if(financeVO.getRevokeApplyUserId() != null) {
    		OrgPO orgPO = orgService.getOrgByUserId(financeVO.getRevokeApplyUserId());
        	
        	financeVO.setRevokeApplyUserName(orgPO.getOrgName());
        	
        	if("1".equals(financeVO.getRevokeVerifyStatus())) {
        		financeVO.setRevokeVerifyRemark(null);
        	}
    	}else {
    		financeVO = new FinanceVO();
    	}
    	
    	financeVO.setRevokeType(authPO.getRevokeType());
    	
    	
    	ResultVO<FinanceVO> vo = ResultVO.success(financeVO);
    	model.put("vo", vo);
    	
    	logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "cancelDetail"));
        return "hos/finance/cancelDetail";
    }


    @RequestMapping("/productSelector")
    public String productSelector(ModelMap model, PageSDTO pageSDTO,ProductSDTO sdto) {
    	logger.info(TrcMsg.getMsg(TrcMsg.METHOD_BEGIN, "productSelector"));
    	PfmVO pfm = ShiroUtils.getAttribute("mcp_pfm");
		OrgPO org = ShiroUtils.getAttribute("org");
		String orgArea = StringUtils.isNotEmpty(org.getCounty())?org.getCounty():StringUtils.isNotEmpty(org.getCity())?org.getCity():org.getProvince();
		
		sdto.setProductStatus("2");//只查已发布
		sdto.setOrgAreaCode(orgArea);
		sdto.setPfmAreaCode(pfm.getAreaCode());
    	sdto.setBankOrgName(XssUtils.replaceXssAll(sdto.getBankOrgName()));
        PageInfo<ProductVO> page = productService.get(sdto, pageSDTO);
        
        
        for(ProductVO vo:page.getList()) {
        	vo.setAmount(DecimalFormatUtil.DecimalFormat2ThreeNumOneComma(vo.getAmount()));
        }
        
        sdto.setBankOrgName(XssUtils.replaceUnXssAll(sdto.getBankOrgName()));
        ResultListVO<ProductVO> vo = ResultListVO.success(page, sdto);
        model.put("vo", vo);
        
        logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "productSelector"));
        return "hos/finance/productSelector";
    }

	@RequestMapping("/productSelectorYBD")
	public String productSelectorYBD(ModelMap model, PageSDTO pageSDTO,ProductSDTO sdto) {
		logger.info(TrcMsg.getMsg(TrcMsg.METHOD_BEGIN, "productSelectorYBD"));
		PfmVO pfm = ShiroUtils.getAttribute("mcp_pfm");
		OrgPO org = ShiroUtils.getAttribute("org");
		String orgArea = StringUtils.isNotEmpty(org.getCounty())?org.getCounty():StringUtils.isNotEmpty(org.getCity())?org.getCity():org.getProvince();

		sdto.setProductStatus("2");//只查已发布
		sdto.setOrgAreaCode(orgArea);
		sdto.setPfmAreaCode(pfm.getAreaCode());
		sdto.setBankOrgName(XssUtils.replaceXssAll(sdto.getBankOrgName()));
		PageInfo<ProductVO> page = productService.getYBD(sdto, pageSDTO);
        for(ProductVO vo:page.getList()) {
        	vo.setAmount(DecimalFormatUtil.DecimalFormat2ThreeNumOneComma(vo.getAmount()));
        }
		
		sdto.setBankOrgName(XssUtils.replaceUnXssAll(sdto.getBankOrgName()));
		ResultListVO<ProductVO> vo = ResultListVO.success(page, sdto);
		model.put("vo", vo);

		logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "productSelectorYBD"));
		return "hos/finance/productSelectorYBD";
	}

    @RequestMapping("/productDetail")
    @ResponseBody
    public ResultVO productDetail(ModelMap model,Long id) {
    	logger.info(TrcMsg.getMsg(TrcMsg.METHOD_BEGIN, "productDetail"));
    	
    	ResultVO<?> r = null;
    	
    	ProductSDTO sdto = new ProductSDTO();
    	sdto.setId(id);
    	List<ProductVO> list = productService.get(sdto);
       
        if(!CollectionUtils.isEmpty(list)) {

        	for(ProductVO productVO:list) {
        		productVO.setAmount(DecimalFormatUtil.DecimalFormat2ThreeNumOneComma(productVO.getAmount()));
        		productVO.setProductName(XssUtils.replaceUnXssAll(productVO.getProductName()));
        		productVO.setBankOrgName(XssUtils.replaceUnXssAll(productVO.getBankOrgName()));
        		productVO.setTimeLimit(XssUtils.replaceUnXssAll(productVO.getTimeLimit()));
        		productVO.setRate(XssUtils.replaceUnXssAll(productVO.getRate()));
        	}
        }
        
    	if(list != null) {
    		r = ResultVO.success(list.get(0));
    	}else {
    		r = ResultVO.fail("数据未找到");
    	}
    	
       
        model.put("vo", r);
        logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "productDetail"));
        return r;
    }

	@RequestMapping("/productDetailYBD")
	@ResponseBody
	public ResultVO productDetailYBD(ModelMap model,Long id) {
		logger.info(TrcMsg.getMsg(TrcMsg.METHOD_BEGIN, "productDetailYBD"));

		ResultVO<?> r = null;

		ProductSDTO sdto = new ProductSDTO();
		sdto.setId(id);
		List<ProductVO> list = productService.getYBD(sdto);

		if(!CollectionUtils.isEmpty(list)) {
//			productService.combo(list);

			for(ProductVO productVO:list) {
				productVO.setAmount(DecimalFormatUtil.DecimalFormat2ThreeNumOneComma(productVO.getAmount()));
				productVO.setProductName(XssUtils.replaceUnXssAll(productVO.getProductName()));
				productVO.setBankOrgName(XssUtils.replaceUnXssAll(productVO.getBankOrgName()));
				productVO.setTimeLimit(XssUtils.replaceUnXssAll(productVO.getTimeLimit()));
				productVO.setRate(XssUtils.replaceUnXssAll(productVO.getRate()));
			}
		}

		if(list != null) {
			r = ResultVO.success(list.get(0));
		}else {
			r = ResultVO.fail("数据未找到");
		}


		model.put("vo", r);
		logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "productDetailYBD"));
		return r;
	}
    
    @GetMapping("/businessRules")
    public String businessRules(ModelMap model) {
		PfmVO pfm = ShiroUtils.getAttribute("mcp_pfm");
		if("0".equals(pfm.getItfType().trim())) {
			return "hos/finance/businessRules";
		} else {
			return "hos/finance/businessRulesYBD";
		}
    }

    @RequestMapping("/businessRulesDownload")
    public String businessRulesDownload(HttpServletRequest request, HttpServletResponse response, ModelMap model) {
		PfmVO pfm = ShiroUtils.getAttribute("mcp_pfm");
		String dirPath = "";
		if(pfm!=null && "0".equals(pfm.getItfType().trim())) {
			dirPath ="/rfpfile/templet/MCPFinanceBusinessRules.docx";
		} else {
			dirPath ="/rfpfile/templet/MCPFinanceBusinessRulesYBD.docx";
		}

        try {
			FileUtil.downloadfile(request, response, dirPath, "医保信息查询授权书.docx");
		} catch (Exception e) {
            log.error("error", e);
		}
        
        return null;
    }

	@RequestMapping ("/updateMiYBD")
	public String updateMiYBD(ModelMap model) {
		logger.info(TrcMsg.getMsg(TrcMsg.METHOD_BEGIN, "HosFinanceController.updateMiYBD"));
		UserPO currentUser = ShiroUtils.getCurrentUser();
		OrgPO  currentOrg =  ShiroUtils.getCurrentOrg();
		OrgYbjPO ybjPO = ShiroUtils.getAttribute("org_ybj");
		PfmVO pfm = ShiroUtils.getAttribute("mcp_pfm");


		Integer mcpMiQueryNum = Integer.parseInt(paramService.getValue("MCP_MI_QUERY_NUM"));//接口调用次数
		Integer ybzhcount = payLogService.getZTSearchSuccessCount(DateUtil.parseStrByYYYYMMDD(LocalDate.now()), DateUtil.parseStrByYYYYMMDD(LocalDate.now().plusDays(1)), currentUser.getOrgId(), currentUser.getOrgId(), ybjPO.getId());
		
		if(ybzhcount >= mcpMiQueryNum){
			return this.alertParentReload(model,"今日查询次数已用尽，请明日再次提交！");
		}

		//查询医保关联信息
        //OrgYbjPO ybj=ybjSerivce.getYbjId(sdto.getTargetOrgId(), pfm.getId());
        OrgYbjPO ybj=ybjSerivce.getOrgYbj(ybjPO.getId(), ybjPO.getAid());
		if(ybj==null){
			return this.alertParentReload(model,"查询失败,未找到医保关联信息");
		}
		if(ybj.getOrgNo()==null || "".equals(ybj.getOrgNo())){
			return this.alertParentReload(model,"查询失败,未找到医保关联信息");
		}

		MiPayLogDTO dto=new MiPayLogDTO();
		dto.setQueryReason(QUERY_REASON);
		dto.setQueryOrgId(currentOrg.getId());
		dto.setQueryUsrId(currentUser.getId());
		dto.setTargetOrgId(currentUser.getOrgId());
		dto.setTargetOrgCode(currentOrg.getOrgCode());
		dto.setAuthId(0L);
		dto.setOptUserId(currentUser.getId());
		dto.setOptType("1");
		dto.setQueryPayState("0");
		dto.setDataType("1");
		dto.setPfmId(pfm.getId());
		dto.setItfType(pfm.getItfType().trim());
		dto.setOrgYbjId(ybjPO.getId());
		
		Map<String, Boolean> counterMap = new HashMap<String, Boolean>();
		counterMap.put(MiPayDataTypeEnum.MI_MAIN.getKey(), false);
		//保存log记录数据
		Integer count=payLogService.saveMiPayLog(dto, counterMap);
		if(count==0){
			return this.alertParentReload(model,"创建查询失败！如有疑问请致电平台客服电话400-009-0001。");
		}

		try{
			OrgSubjectInfoDto orgSubjectInfoDto = new OrgSubjectInfoDto();
			orgSubjectInfoDto.setMiOrgCode(ybjPO.getOrgNo());
			orgSubjectInfoDto.setPfmId(dto.getPfmId());
			orgSubjectInfoDto.setLogId(dto.getId());
			ResultVO<String> result=orgSubjectInfoService.queryOrgSubjectInfo(orgSubjectInfoDto);
//			ResultVO<String> result=new ResultVO<>(ResultVO.SUCCESS);   //测试语句
			if(!ResultVO.SUCCESS.equals(result.getCode())){
				return this.alertParentReload(model,"主体信息查询失败，请稍后查询！如有疑问请致电平台客服电话400-009-0001。");
			}
			dto.setQueryPayState("1");
			payLogService.updateById(dto.getId(),dto);
		}catch (Exception ex){
			log.error(ex.getMessage());
		}

		logger.info(TrcMsg.getMsg(TrcMsg.METHOD_END, "HosFinanceController.updateMiYBD"));

		return this.alertParentReload(model,"操作成功");
	}
    
}